<?php
/***
 * 产品模板API Service
 *
 *
 * @author    lanhongjie <lanhj@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */


namespace App\Services\ProductTempService;


use App\Services\BrandService\BrandToolService;
use App\Services\ColourService\ColourTool;
use App\Services\ImgServices\ImgTool;
use App\Services\ProdTempCategoryService\ProdTempCategoryTool;
use App\Services\ProdTempCreationMasksService\CreationMaskApiService;
use App\Services\ProductsService\ProductTool;
use App\Services\Tool\GeneralTool;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ProductTempApiService
{
     protected $productTempTool;
     protected $creationMaskApiSer;
     protected $productTool;
    /**
     * ProductTempApiService constructor.
     */
    public function __construct(ProductTempTool $productTempTool,
                                CreationMaskApiService $creationMaskApiSer,
                                ProductTool $productTool)
    {
        $this->productTempTool=$productTempTool;
        $this->creationMaskApiSer=$creationMaskApiSer;
        $this->productTool=$productTool;

    }

    /***
     * 获取创作启动蒙板
     * @param array $data
     * @return array
     */
    public function getCreationMasks(array $data){
        try{
        $per_page=empty($data['per_page'])?6:$data['per_page'];
        $creation_masks=$this->creationMaskApiSer->getCreationMasks($per_page);
        foreach ($creation_masks as $creation_mask){
            $creation_mask->original_image=ImgTool::getImgUrlByImgPath($creation_mask->original_image);
        }
        $creation_masks_arr=$creation_masks->toArray();
        if(sizeof($creation_masks_arr['data'])!=0){
            return array('data' => $creation_masks_arr['data'], 'current_page' => $creation_masks_arr['current_page'],
                'per_page' => $creation_masks_arr['per_page'], 'total_page' => $creation_masks_arr['last_page'],
                'total' => $creation_masks_arr['total']);
        }else{
            return array('data' => array(), 'current_page' =>1, 'per_page' =>0, 'total_page' =>0, 'total' => 0);
        }
        }catch (\Exception $e){
            Log::info($e);
            return array('data' => array(), 'current_page' => 1,
                'per_page' => $per_page, 'total_page' => 0,
                'total' =>0);
        }
    }

    /***
     * 获取某一产品模板下创作模板
     * @param array $data
     * @return array
     */
    public function getAuthoringTempByTempId(array $data){
        try{
        $isAndroid=ProductTempTool::isAndroidByPlatform($data['platform']);
        $user_id  =$data['user_id'];
        $product_draft_ids=array();
        $platform=$data['platform'];
        $per_page=empty($data['per_page'])?10:$data['per_page'];
        $product_temp_id=$data['product_temp_id'];
        $product_temp=$this->productTempTool->getProdTempSimpleInfoByProdTempId($product_temp_id);
        if(empty($product_temp)){
            return array('data' => (object)array(), 'current_page' =>1, 'per_page' =>0, 'total_page' =>0, 'total' => 0);
        }
        //产品模板对应下的颜色
        $product_temp_colours=$this->productTempTool->getProdTempColourByProdTempId($product_temp_id,$per_page);
        if($product_temp_colours===null){
            return array('data' => (object)array(), 'current_page' =>1, 'per_page' =>0, 'total_page' =>0, 'total' => 0);
        }
        if($product_temp->postage==0){
          $postage='免邮';
        }else{
            $postage= GeneralTool::priceFormat($product_temp->postage);
        }
        $product_temp->postage=$postage;
        $product_temp->temp_intro_h5_url=$isAndroid?(env("CURRENT_HTTP_DOMAIN").'/api/temp-detail?temp_id='.$product_temp_id):asset('api/temp-detail?temp_id='.$product_temp_id);
        foreach ($product_temp_colours as $temp_colour){
            if($temp_colour->original_price==0){
                $original_price='免费';
            }else{
                $original_price=GeneralTool::priceFormat($temp_colour->original_price).'';
            }
            $temp_colour->original_price=$original_price;
            $temp_colour->preferential_price=$original_price;
            $temp_colour->has_preferential =0;
            $temp_colour->colour_name='';
            $temp_colour->colour_code='';
            $temp_colour->colour_image='';
            $colour=ColourTool::getColourSimpleInfoByColourId($temp_colour->colour_id);
            if(!empty($colour)){
                $temp_colour->colour_name=$colour->colour_name;
                $temp_colour->colour_code=$colour->colour_code;
                $temp_colour->colour_image=$colour->colour_image;
            }
            $temp_custom_zones=$this->productTempTool->getProdTempCustomZonesByProdTempColourId($temp_colour->id,1,$platform);
            $temp_colour->temp_custom_zones=empty($temp_custom_zones)?array():$temp_custom_zones;
        }
        $temps_arr=$product_temp_colours->toArray();
        $product_temp->postage=$postage;
        $product_temp->temp_colours=$temps_arr['data'];
        if(!empty($user_id)){
            $product_draft_ids=$this->productTool->has_draft_by_product_temp_id($user_id,$product_temp_id);
        }
        $product_temp->product_draft_ids=$product_draft_ids;
        $product_temp->has_drafts=(count($product_draft_ids)==0)?0:1;
        if(!empty($temps_arr['data'])){
            return array('data' => $product_temp, 'current_page' => $temps_arr['current_page'],
                'per_page' => $temps_arr['per_page'], 'total_page' => $temps_arr['last_page'],
                'total' => $temps_arr['total']);
        }else{
            return array('data' => $product_temp, 'current_page' =>1, 'per_page' =>0, 'total_page' =>0, 'total' => 0);
        }
        }catch (\Exception $e){
            Log::info($e);
            return array('data' => array(), 'current_page' => 1,
                'per_page' => $per_page, 'total_page' => 0,
                'total' =>0);
        }
    }

    /***
     * 获取产品模板各个颜色，以及打印区域图片
     * @param $product_temp_id
     * @return array
     */
    public function tempDetailColours($product_temp_id){
        try{
            $product_temp=$this->productTempTool->getProdTempSimpleInfoByProdTempId($product_temp_id);
            if(empty($product_temp)){
                return array('data' => (object)array(), 'current_page' =>1, 'per_page' =>0, 'total_page' =>0, 'total' => 0);
            }
            //产品模板对应下的颜色
            $product_temp_colours=ProductTempTool::productTempColoursByProductTempId($product_temp_id,1);
            if(empty($product_temp_colours)){
                return array();
            }
            foreach ($product_temp_colours as $temp_colour){
                if($temp_colour->original_price==0){
                    $original_price='免费';
                }else{
                    $original_price=GeneralTool::priceFormat($temp_colour->original_price).'';
                }
                $temp_colour->original_price=$original_price;
                $temp_colour->preferential_price=$original_price;
                $temp_colour->has_preferential =0;
                $temp_colour->colour_name='';
                $temp_colour->colour_code='';
                $temp_colour->colour_image='';
                $colour=ColourTool::getColourSimpleInfoByColourId($temp_colour->colour_id);
                if(!empty($colour)){
                    $temp_colour->colour_name=$colour->colour_name;
                    $temp_colour->colour_code=$colour->colour_code;
                    $temp_colour->colour_image=$colour->colour_image;
                }
                $temp_custom_zones=$this->productTempTool->getProdTempCustomZonesImagesByProdTempColourId($temp_colour->id,1,1);
                $temp_colour->temp_custom_zones=empty($temp_custom_zones)?array():$temp_custom_zones;
            }
            return $product_temp_colours;
        }catch (\Exception $e){
            Log::info($e);
            return array();
        }
    }
    /****
     * 获取产品模板分类下的,产品模板Tag
     * @param array $data
     * @return array
     */
    public function getAuthoringTempTagsByTempCategoryId(array  $data){
        try{
        $per_page=$data['per_page'];
        $temp_category_id=$data['temp_category_id'];
        $product_temp_ids=ProductTempTool::getProdTempIdsByCategoryId($temp_category_id);
        if(!empty($product_temp_ids)){
            //此时tag_id有可能是顶级，有可能是是某一个tag_id下的子tag
            $tag_ids=DB::table('tag_resource_maps')->where(array('state'=>1,'app_id'=>2,'is_show'=>1))
                ->whereIn('resource_id',$product_temp_ids)
                ->pluck('tag_id')
                ->toArray();
            $has_one_level_tag_ids=array();
            foreach ($tag_ids as $tag_id){
                $top_tag_id=ProductTempTool::getTopTagIdByTagId($tag_id);
                if(!empty($top_tag_id)){
                    $has_one_level_tag_ids[]=$top_tag_id;
                }
            }
            $tag_special_ids=DB::table('tags')->where(array('state'=>1,'app_id'=>2,'tag_type'=>1))
                ->pluck('id')
                ->toArray();
            $tag_ids=array_merge($has_one_level_tag_ids,$tag_special_ids);
            $tag_ids=array_unique($tag_ids);
            if(!empty($tag_ids)){
                $tags=DB::table('tags')->where(array('state'=>1,'app_id'=>2))
                    ->whereIn('id',$tag_ids)
                    ->select('id as tag_id','name','has_sub_tag','original_image')
                    ->orderBy('tag_type','ASC')
                    ->orderBy('sort','DESC')
                    ->paginate($per_page);
                foreach ($tags as $tag){
                    if(!empty($tag->original_image)){
                        $original_image=ImgTool::getImgUrlByImgPath($tag->original_image);
                        $tag->original_image=empty($original_image)?'':$original_image;
                    }
                }
                $tags_arr=$tags->toArray();
                if(sizeof($tags_arr['data'])>0){
                    return array('data' => $tags_arr['data'], 'current_page' => $tags_arr['current_page'],
                        'per_page' => $tags_arr['per_page'], 'total_page' => $tags_arr['last_page'],
                        'total' => $tags_arr['total']);
                }
            }
        }
        return array('data' => array(), 'current_page' => 1,
            'per_page' => $per_page, 'total_page' => 0,
            'total' =>0);
        }catch (\Exception $e){
            Log::info($e);
            return array('data' => array(), 'current_page' => 1,
                'per_page' => $per_page, 'total_page' => 0,
                'total' =>0);
        }
    }

    /***
     * 获取创作模板下的模板列表
     * @param array $data
     * @return array
     */
    public function getAuthoringTempListByTempTagId(array $data)
    {
        try{
        $per_page=$data['per_page'];
        $tag_id=$data['tag_id'];
        $temp_category_id=$data['temp_category_id'];
        $product_temp_ids=$this->productTempTool->getAllProductTempIdsByCategoryId($temp_category_id);
        $tag=ProductTempTool::getTagByTagId($tag_id);
        if(empty($tag)){
            return array('data' => array(), 'current_page' => 1,
                'per_page' => $per_page, 'total_page' => 0,
                'total' =>0);
        }
        if($tag->tag_type===1){
            //产品模板分类下的所有产品模板
            $product_temp_ids=self::getAllProductTempIdsByTempCategoryId($temp_category_id);
        }else{
            if($tag->has_sub_tag===0){
                //产品模板标签下所有产品模板Id
                $product_temp_ids=self::getProductTempIdsByTagId($tag_id);
            }
        }
        if(empty($product_temp_ids)){
            return array('data' => array(), 'current_page' => 1,
                'per_page' => $per_page, 'total_page' => 0,
                'total' =>0);
        }
        $order_by_key='created_at';
        if($tag->sort_type===1){
            $order_by_key='used_num';
        }
        $product_temps=DB::table('product_temps')->where(array('state'=>1,'product_temp_category_id'=>$temp_category_id))
            ->whereIn('product_temp_id',$product_temp_ids)
            ->orderBy($order_by_key,'DESC')
            ->orderBy('sort','DESC')
            ->select('product_temp_id','name','product_temp_category_id','brand_id','used_num','postage')
            ->paginate($per_page);
        foreach ($product_temps as $product_temp){
            $product_temp->temp_colours=array();
            $product_temp_colour=$this->getProdTempBriefDetailsByProdTempId($product_temp->product_temp_id);
            if(!empty($product_temp_colour)){
                $product_temp->temp_colours[]=$product_temp_colour;
            }

        }
        $product_temps_arr=$product_temps->toArray();
        if(sizeof($product_temps_arr['data'])>0){
            return array('data' => $product_temps_arr['data'], 'current_page' => $product_temps_arr['current_page'],
                'per_page' => $product_temps_arr['per_page'], 'total_page' => $product_temps_arr['last_page'],
                'total' => $product_temps_arr['total']);
        }
        return array('data' => array(), 'current_page' => 1,
            'per_page' => $per_page, 'total_page' => 0,
            'total' =>0);
        }catch (\Exception $e){
            Log::info($e);
            return array('data' => array(), 'current_page' => 1,
                'per_page' => $per_page, 'total_page' => 0,
                'total' =>0);
        }
    }
    public function getTempListByTempTagId(array $data)
    {
        try{
            $per_page=$data['per_page'];
            $tag_id=$data['tag_id'];
            $temp_category_id=$data['temp_category_id'];
            $tag=ProductTempTool::getTagByTagId($tag_id);
            if(empty($tag)){
                return array('data' => array(), 'current_page' => 1,
                    'per_page' => $per_page, 'total_page' => 0,
                    'total' =>0);
            }
            $product_temp_ids=$this->productTempTool->getAllProductTempIdsByCategoryId($temp_category_id);
            $product_temps=DB::table('tag_resource_maps')->where(array('state'=>1,'tag_id'=>$tag_id,'app_id'=>2,'is_show'=>1))
                ->whereIn('resource_id',$product_temp_ids)
                ->distinct()
                ->orderBy('sort','ASC')
                ->select('resource_id as product_temp_id')
                ->paginate($per_page)
                ->toArray();
            foreach ($product_temps['data'] as $key=> $product_temp){
                $product_temp_obj=DB::table('product_temps')
                    ->where('product_temp_id',$product_temp->product_temp_id)
                    ->select('product_temp_id','name','product_temp_category_id','brand_id','used_num','postage')
                    ->first();
                if(empty($product_temp_obj)){
                    unset($product_temps['data'][$key]);
                }
                $product_temp->name=$product_temp_obj->name;
                $product_temp->product_temp_category_id=$product_temp_obj->product_temp_category_id;
                $product_temp->brand_id=$product_temp_obj->brand_id;
                $product_temp->used_num=$product_temp_obj->used_num;
                $product_temp->postage=$product_temp_obj->postage;
                $product_temp->product_temp_id=$product_temp_obj->product_temp_id;
            }
            foreach ($product_temps['data'] as $product_temp){
                $product_temp->temp_colours=array();
                $product_temp_colour=$this->getProdTempBriefDetailsByProdTempId($product_temp->product_temp_id);
                if(!empty($product_temp_colour)){
                    $product_temp->temp_colours[]=$product_temp_colour;
                }

            }
            if(sizeof($product_temps['data'])>0){
                return array('data' => $product_temps['data'], 'current_page' => $product_temps['current_page'],
                    'per_page' => count($product_temps['data']), 'total_page' => $product_temps['last_page'],
                    'total' => $product_temps['total']);
            }
            return array('data' => array(), 'current_page' => 1,
                'per_page' => $per_page, 'total_page' => 0,
                'total' =>0);
        }catch (\Exception $e){
            Log::info($e);
            return array('data' => array(), 'current_page' => 1,
                'per_page' => $per_page, 'total_page' => 0,
                'total' =>0);
        }
    }
    /***
     * 获取产品分类下，所有产品模板ID
     * @param $temp_category_id
     * @return array
     */
    public function getAllProductTempIdsByTempCategoryId($temp_category_id){
        if(empty($temp_category_id)){
            return array();
        }
        $product_temp_ids=DB::table('product_temps')->where(array('state'=>1,'product_temp_category_id'=>$temp_category_id))
            ->pluck('product_temp_id')
            ->toArray();
        return $product_temp_ids;
    }

    /***
     * 获取标签 某一标签下的所有产品模板Id
     * @param $tag_id
     * @return array
     */
    public function getProductTempIdsByTagId($tag_id){
        if(empty($tag_id)){
            return array();
        }
        $product_temp_ids=DB::table('tag_resource_maps')->where(array('state'=>1,'tag_id'=>$tag_id,'app_id'=>2,'is_show'=>1))
            ->distinct()
            ->pluck('resource_id')
            ->toArray();
        return $product_temp_ids;
    }

    /***
     * 获取产品模板中的排在第一的颜色
     * @param $product_temp_id
     * @return null
     */
    public function getProdTempBriefDetailsByProdTempId($product_temp_id){
        $product_temp_colour=$this->productTempTool->getProdTempFirstColourByProdTempId($product_temp_id);
        if(!empty($product_temp_colour)){
            if($product_temp_colour->original_price==0){
                $original_price='免费';
            }else{
                $original_price=GeneralTool::priceFormat($product_temp_colour->original_price).'';
            }
            $product_temp_colour->original_price=$original_price;
            $product_temp_colour->preferential_price=$original_price;
            $product_temp_colour->has_preferential =0;
            $platform='';
            $temp_custom_zones=$this->productTempTool->getProdTempCustomZonesByProdTempColourId($product_temp_colour->id,0,$platform);
            $product_temp_colour->temp_custom_zones=empty($temp_custom_zones)?array():$temp_custom_zones;
            $colour=ColourTool::getColourSimpleInfoByColourId($product_temp_colour->colour_id);
            $product_temp_colour->colour_name='';
            $product_temp_colour->colour_code='';
            $product_temp_colour->colour_image='';
            if(!empty($colour)){
                $product_temp_colour->colour_name=$colour->colour_name;
                $product_temp_colour->colour_code=$colour->colour_code;
                $product_temp_colour->colour_image=$colour->colour_image;
            }
        }
        return $product_temp_colour;
    }
    public function goodsDetail($product_id)
    {
        try{
        if(empty($product_id)){
            return false;
        }
        $product=$this->productTool->get_prod_temp_colour_size_by_product_id($product_id);
        $product_attr_maps=array();
        if(!empty($product)){
            $product_temp_id=$product->product_temp_id;
            $colour_name=(isset($product->colour)&&(isset($product->colour->colour_name)))?$product->colour->colour_name:'';
            $brand_id=ProductTempTool::getProdTempBrandIdByProdTempId($product_temp_id);
            $brand_name='';
            if(!empty($brand_id)){
                $brand_name=BrandToolService::getBrandNameByBrandId($brand_id);
            }
            $crowd_name=ProductTempTool::getProdTempCrowdNameByProdTempId($product_temp_id);
            $product_attr_maps[0]=(object)array('attr_value'=>$brand_name,'attr_name'=>'品牌');
            $product_attr_maps[1]=(object)array('attr_value'=>$colour_name,'attr_name'=>'颜色');
            $product_attr_maps[2]=(object)array('attr_value'=>$crowd_name,'attr_name'=>'群体');
            $product_temp_attr_maps=$this->getProduTempAttrMaps($product_temp_id);
            $product_attr_maps=array_merge($product_attr_maps,$product_temp_attr_maps);
        }else{
            return false;
        }
        $temp_size_format=ProductTempTool::goodsDetailGetProdTempSizeListByProdTempId($product_temp_id);
        if($temp_size_format===null){
            return false;
        }
        return array('temp_size_format'=>$temp_size_format,'product_attr_maps'=>$product_attr_maps);
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    public function tempDetail($product_temp_id)
    {
        try{
            if(empty($product_temp_id)){
                return false;
            }
            $product_attr_maps=array();
            $crowd_name=ProductTempTool::getProdTempCrowdNameByProdTempId($product_temp_id);
            $product_attr_maps[0]=(object)array('attr_value'=>$product_temp_id,'attr_name'=>'编号');
            $product_attr_maps[2]=(object)array('attr_value'=>$crowd_name,'attr_name'=>'群体');
            $product_temp_attr_maps=$this->getProduTempAttrMaps($product_temp_id);
            $product_attr_maps=array_merge($product_attr_maps,$product_temp_attr_maps);
            $temp_size_format=ProductTempTool::goodsDetailGetProdTempSizeListByProdTempId($product_temp_id);
            if($temp_size_format===null){
                return false;
            }
            return array('temp_size_format'=>$temp_size_format,'product_attr_maps'=>$product_attr_maps);
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /****
     * 获取商品属性
     * @param $product_temp_id
     * @return array
     */
    public function getProduTempAttrMaps($product_temp_id){
        if(empty($product_temp_id)){
            return array();
        }
        $attr_maps=DB::table('product_temp_attr_maps')->where(array('product_temp_id'=>$product_temp_id))
            ->orderBy('sort','ASC')
            ->select('attr_value','attr_name')
            ->get()
            ->toArray();
        return $attr_maps;
    }
}